
** Loading data - generated in dofile: data05
use "$data\minwage_data5_estimation_2012_2015.dta", clear

* Creating a dataset consiting of  ID
* Ready for merge with DST data on parental ids and earnings
bysort pnr: keep if _n == 1
keep pnr cohort 

** Finding parental id
forval c = 1992/1999{
	preserve
	keep if cohort == `c'
	
	local t = `c' + 13 // finding parental id at age 13
	local tm1 = `t' - 1 // age 12
	local tp1 = `t' + 1 // age 14
	
	** data on parental id and age (just to check everything looks ok)
	merge 1:1 pnr using "E:\Data\rawdata\703788\bef`t'", nogen keep(match master) keepus(far_id mor_id alder reg*) // the yr you turn 16 2008-2015
	rename alder`t' alder
	rename reg`t' region
	rename pnr g0_pnr 
	
	** merging parental earnings information (age child age 12-13-14)
	foreach var in far_id mor_id{
		rename `var' pnr	
		forval y = `tm1'/`tp1'{
			merge m:1 pnr using "E:\Data\RAWdata\703788\indh`y'", nogen keep(match master) keepus(loenmv`y') 
			rename loenmv`y' `var'_loenmv_`y'
		}
		rename pnr `var'
	}
	** Finding average earnings 3-year average earnings from parents
	egen avg_parental_earnings = rowmean(far_id_loenmv_`tm1' far_id_loenmv_`t' far_id_loenmv_`tp1' mor_id_loenmv_`tm1' mor_id_loenmv_`t' mor_id_loenmv_`tp1')
	drop far_id_* mor_id_*
	xtile avg_p_earn_rank = avg_parental_earnings, nq(10) // generating cohort specifict parental earnings deciles
	
	rename g0_pnr pnr
	** saving cohort specific data sets on parental earnings (deciles)
	save "$data\parental_income_p10_coh`c'.dta", replace
	restore
}
	
** collecting the cohort specific results in one dataset	
use "$data\parental_income_p10_coh1992.dta", clear
forval c = 1993/1999{
	append using "$data\parental_income_p10_coh`c'.dta",
}
** final data on parental earnings deciles
save "$data\parental_income_ptiles10.dta", replace
